package com.proscenic.oauth2.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.RequestMatcher;

@Configurable
public class AuthorizationServerConfig {
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity security) throws Exception {
        // Authorization Server 默认配置
        this.oAuth2AuthorizationServerConfigurer(security);
        return security.formLogin(Customizer.withDefaults()).build();
    }

    private void oAuth2AuthorizationServerConfigurer(HttpSecurity security) throws Exception {
        OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>();
        RequestMatcher matcher = authorizationServerConfigurer.getEndpointsMatcher();

        security.requestMatcher(matcher)
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .csrf().disable().cors().disable()
                .apply(authorizationServerConfigurer);

    }

//    @Bean
//    JdbcRegisteredClientRepository jdbcRegisteredClientRepository(JdbcTemplate jdbcTemplate, String clientId){
//        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
//         registeredClientRepository.findByClientId(clientId);
//    }

}
